var app = getApp();
import qs from './qs.js'
import {
  urlConfig
} from './url_config.js'
let requestTask = []
const isPending = (url) => {
  for (let p in requestTask) {
    if (requestTask[p].url === url) { //当前请求在数组中存在时执行函数体
      requestTask[p].task.abort()
      return true
    }
  }
  return false
}
const removePedding = (url) => {
  for (let p in requestTask) {
    if (requestTask[p].url === url) {
      requestTask.splice(p, 1)
    }
  }
}

function lgRequest(url, postData, {
  doSuccess,
  doFail,
  doComplete,
  hostType = 'normal',
  errAlert = true, //报错时是否显示弹窗
  isNeedAuth = true, //是否需要登录
  paramsReverse = false //基础参数用本组件还是页面
} = {}) {
  let urlApi = urlConfig[url]
  let api = urlApi.url
  let query = urlApi.query
  if (!api) {
    console.log(url + '请求不合法')
    return
  }
  if (!getApp()) {
    console.log('getApp()  未初始化')
    setTimeout(() => {
      lgRequest(...arguments)
    }, 500)
    return
  }
  var server = getApp().globalData.server
  if (hostType == 'normal') {
    server = getApp().globalData.server
  } 
  let requestUrl = server + api
  if(query){
    let queryList = Object.values(postData)
    let queryStr = queryList.join('/')
    requestUrl = requestUrl+'/'+queryStr
  }
  let requestTaskItem = wx.request({
    url: requestUrl,
    data: postData,
    method: urlApi.method,
    // header: {
    //   //设置参数内容类型为json
    //   // 'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    //   'content-type':'application/json; charset=UTF-8'
    // },
    header: urlApi.method == 'get' ? {
      // accessToken
      'Authorization': wx.getStorageSync('token'),
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      "Content-Type": "application/json; charset=UTF-8"
    } : {
      'Authorization': wx.getStorageSync('token'),
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json; charset=UTF-8'
    },
    success: function (res) {
      let r = res.data
      // if (!r.status || (r.status != 200 && errAlert)) {
      //   wx.showModal({
      //     title: '提示',
      //     content: r.msg || `${urlApi.errMsg}失败`,
      //     success(res) {
      //       if (res.confirm) { } else if (res.cancel) {
      //         console.log('用户点击取消')
      //       }
      //     }
      //   })
      //   return
      // }
      // if (typeof doSuccess == "function") {
        doSuccess(r);
      // }
    },
    fail: function (res) {
    },
    complete: function (r) {
      if(r.data.code==401){
        
        wx.navigateTo({
                    url: '/pages/login/login',
          //           url: '/pages/home/home',
                  })
      }
      if (typeof doComplete == "function") {
        doComplete(r);
      }
    }
  });
}
module.exports.lgRequest = lgRequest;